import os
import sys
from ccpm.pmbase import PluginBase
from ccpm.glan import Lan
from ccpm.constants import Constant
from ccpm.conffac import GConf, PluginConf
from ccpm.net import NetUtil
from ccpm.auth.gitee_auth import GiteeLogin
from ccpm.auth.heyzf_auth import HeyzfLogin
from ccpm.model.modelusr import ModelUsr


class eAccountType:
    gitee = 1
    github = 2


class AddUserPlugin(PluginBase):

    PLUGIN_INFO = dict(
        name="adduser",
        help="adduser support <gitee.com> <github.com> count!"
    )

    def __init__(self):
        if not hasattr(self, "_inc"):
            self._inc = super().__init__(self.PLUGIN_INFO)
        return self._inc

    def parser_config(self, argparser):
        super().parser_config(argparser)
        argparser.add_argument(
            "-u", dest="user", help=Lan.p(self.name, "PARAMS_USR_DESC"))
        argparser.add_argument(
            "-p",  dest="pwd", help=Lan.p(self.name, "PARAMS_PWD_DESC"))

    def run(self, argpars):
        super().run(argpars)
        usr = argpars.user
        pwd = argpars.pwd
        authtype = GConf().get("auth_type")
        if not (usr and pwd):
            self.err_break(Lan.p(self.name, "ERR_PWDLOGIN_INPUT", authtype))
        
        ModelUsr().clear()
        if authtype == "gitee":
            self.__login_gitee(usr, pwd)
        elif authtype == "heyzf":
            self.__login_heyzf(usr, pwd)

    def __login_gitee(self, usr, pwd):
        client_id = PluginConf().get("_gitee").clientid
        client_sec = PluginConf().get("_gitee").secret
        (issuc, invoice) = GiteeLogin.post_acctoken(
            client_id, client_sec, usr, pwd)
        if issuc:
            invoice["authtype"] = "gitee"
            ModelUsr().set_dic(invoice)
            ModelUsr().flush()
            self.logger.info("add gitee user suc!")
        else:
            self.logger.error("add gitee user failed!")

    def __login_heyzf(self, usr, pwd):
        (issuc, invoice) = HeyzfLogin.post_acctoken(
            usr, pwd
        )
        if issuc:
            invoice["authtype"] = "heyzf"
            gid = invoice.get("data")["user_info"]["gid"]
            del invoice.get("data")["user_info"]
            invoice.get("data")["gid"] = gid
            ModelUsr().set_dic(invoice.get("data"))
            ModelUsr().flush()
            self.logger.info("add heyzf user suc!")
        else:
            self.logger.error("add heyzf user failed! err:%s" %
                              invoice.get("desc"))


__all__ = [
    "WhoamiPlugin"
]
